package com.macaline.concurrent.demo;


import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class ShareRe {

    private Lock lock = new ReentrantLock();
    private Condition c1 = lock.newCondition();
    private Condition c2 = lock.newCondition();
    private Condition c3 = lock.newCondition();


    private int flag = 1;

    public void print1(int num) throws InterruptedException {
        lock.lock();
        try {
            while (flag != 1){
                c1.await();
            }
            System.out.println(Thread.currentThread().getName() + "第" + num + "轮print1");
            flag = 2;
            c2.signalAll();
        }finally {
            lock.unlock();
        }
    }

    public void print2(int num) throws InterruptedException {
        lock.lock();
        try {
            while (flag != 2){
                c2.await();
            }
            System.out.println(Thread.currentThread().getName() + "第" + num + "轮print2");
            flag = 3;
            c3.signalAll();
        }finally {
            lock.unlock();
        }
    }
    public void print3(int num) throws InterruptedException {
        lock.lock();
        try {
            while (flag != 3){
                c3.await();
            }
            System.out.println(Thread.currentThread().getName() + "第" + num + "轮print3");
            flag = 1;
            c1.signalAll();
        }finally {
            lock.unlock();
        }
    }
}

public class ThreadComm {



    public static void main(String[] args) {
        ShareRe threadComm = new ShareRe();
        new Thread(()->{
            try {
                for (int i = 0; i < 3; i++) {
                    threadComm.print1(i + 1);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "AA").start();


        new Thread(()->{
            try {
                for (int i = 0; i < 3; i++) {
                    threadComm.print2(i + 1);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "BB").start();

        new Thread(()->{
            try {
                for (int i = 0; i < 3; i++) {
                    threadComm.print3(i + 1);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "CC").start();



    }

}
